package org.nidy.programexercise.ReflexExercise;

import org.nidy.programexercise.MethodCitation.Student;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.alibaba.fastjson.JSON;


public class ReflexExercise {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        System.out.println("===================获取类字节码=========================");
        Class  aClass = Class.forName("org.nidy.programexercise.MethodCitation.Student");
        System.out.println("===================获取所有方法=========================");
        Method[] declaredMethods = aClass.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println(declaredMethod);
        }
        System.out.println("===================获取所有字段=========================");
        Field[] fields = aClass.getDeclaredFields();
        for (Field declaredField : fields) {
            System.out.println(declaredField);
        }
        System.out.println("===================获取Class对象=========================");
        Class<Student> studentClass = Student.class;
        Constructor<Student> constructor = studentClass.getConstructor(String.class, int.class);
        Student student = constructor.newInstance("Nidy", 18);
        System.out.println(student);
        //获取Print方法，并调用
        studentClass.getDeclaredMethod("print").invoke(student);
        Field nameField = studentClass.getDeclaredField("name");
        //调用私有字段，需要设置访问权限
        nameField.setAccessible(true);
        System.out.println("name = " + nameField.get(student));
        System.out.println("===================Json转对象=========================");
        String json="{\"name\":\"Nidy\",\"age\":18}";
        Student student1 = JSON.parseObject(json, Student.class);
        System.out.println(student1);




    }
}
